package campeonatofutebol.persistencia;

import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import campeonatofutebol.bean.RepositorioDeDados;



public class DBAdapter {
	public static SQLiteDatabase database;
	private DbHelper dbHelper;
	private String[] timesFavoritos = {/*DbHelper.NOME_TIME*/};


	public DBAdapter(Context context) {
		dbHelper = new DbHelper(context);
	}



	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();

	}



	public void close() {
		dbHelper.close();
		database.close();
	}

	public SQLiteDatabase getDatabase() {
		return database;
	}



	public void addTime(String nomeTime){
		if(!timeJaFavoritado(nomeTime)){
			SQLiteDatabase database = DBAdapter.database;
			ContentValues timesFavoritados = new ContentValues();
			timesFavoritados.put(DbHelper.NOME_TIME, nomeTime);
			database.insert(DbHelper.TABLE_TIME_NOME, null, timesFavoritados);
			System.out.println("Time adicionado em favoritos no BD" + nomeTime);
			 RepositorioDeDados.getInstance().getFavoritos().addAll(this.getTimesFavoritados());
		}
	}


	public List<String> getTimesFavoritados(){
		Cursor cursor = database.rawQuery("select " + DbHelper.NOME_TIME + " from " + DbHelper.TABLE_TIME_NOME, null);
		List<String> list = new ArrayList<String>();
		if(cursor.getCount() > 0){
			while(!cursor.isLast()){
				cursor.moveToNext();
				String nomeTime = cursor.getString(cursor.getColumnIndex(DbHelper.NOME_TIME));
				list.add(nomeTime);
			}
			cursor.close();
		}
		return list;
	}

	public boolean timeJaFavoritado(String time) {
		return getTimesFavoritados().contains(time);
	}

	public void deletaTimeFavorito(String nomeTime){
		database.delete(DbHelper.TABLE_TIME_NOME, DbHelper.NOME_TIME + "='" + nomeTime + "'", null);
		imprimeFavoritos();
	}

	private void imprimeFavoritos(){
		List<String> favoritos = getTimesFavoritados();
		for (String favorito : favoritos) {
			System.out.println("Nome favorito: " + favorito);
		}
	}
	/*public void imprimeTimes(){
		Cursor c = this.getTimesFavoritados();
		String nomeTimes = c.getString(c.getColumnIndex(DbHelper.NOME_TIME));
		while(!c.isLast()){
			String nomeTime = c.getString(c.getColumnIndex(DbHelper.NOME_TIME));
			System.out.println(nomeTime);
			c.moveToNext();

		}
		c.close();
	}*/
}